﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using StateGrid;
using StateGrid.HYBZ;
using StateGrid.User;
using StateGrid.GlobalVariables;
using iTextSharp.text.pdf;
using StateGrid.OperationLog;

public partial class AddPM : System.Web.UI.Page
{
    /// <summary>
    /// 行业标准操作对象
    /// </summary>
    private HYBZ_DAO hybzDAO = new HYBZ_DAO();

    /// <summary>
    /// 日志操作对象
    /// </summary>
    private OperationLog_DAO operationLogDAO = new OperationLog_DAO();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!UserManageDAO.IsLogin((User)Session["login"]))
        {
            GlobalMethod.RedirectLogin(Response);
            return;
        }

        if (!this.IsPostBack)
        {
            this.BindData();
        }

    }

    /// <summary>
    /// 绑定初始化数据
    /// </summary>
    private void BindData()
    {
        String message = null;

        User user = (User)Session["login"];
        //登陆超时则退到登录页
        if (null == user)
        {
            Response.Write(" <script> top.location = '" + GlobalResource.LOGIN_PAGE + "' </script> ");
            return;
        }
        //登录人
        this.dlrTextBox.Text = user.name;

        String bzwh = HttpUtility.UrlDecode(Request["bzwh"]);
        if (null == bzwh || "".Equals(bzwh))
        {
            //获取分类编码
            String flbm = Request["flbm"];
            //年份
            String nf = Request["nf"];

            HYBZ_FL hybzFL = null;
            //验证年份
            if (null == nf || nf.Length != 4)
            {
                message = "错误：年份信息有误";
                Response.Redirect(GlobalResource.ERROR_PAGE + "?message=" + message);
                return;
            }

            if (null == flbm || "".Equals(flbm))
            {
                message = "错误：分类编码为空";
                Response.Redirect(GlobalResource.ERROR_PAGE + "?message=" + message);
                return;
            }
            else
            {
                hybzFL = hybzDAO.GetHYBZ_FLByFlbm(flbm);
                if (null == hybzFL)
                {
                    message = "错误：没有找到对应的分类编码";
                    Response.Redirect(GlobalResource.ERROR_PAGE + "?message=" + message);
                    return;
                }
            }

            //设置返回按钮链接
            this.backHyperLink.NavigateUrl = GlobalHYBZ.LISTPM_PAGE + "?catalog=" + flbm;

            HYBZ_PM hybzPM = this.hybzDAO.getMaxHYBZ_PM(flbm, nf);

            //分类编码
            this.flbmTextBox.Text = hybzFL.flbm;
            //分类名称
            this.flmcTextBox.Text = hybzFL.flmc;
            //标准文号
            this.bzwhTextBox.Text = flbm.Substring(2, 2) + "******-" + nf;
            //实施年份
            this.ssnfTextBox.Text = nf;

            //版本性质
            this.bbxzTextBox.Text = "";
            //中文名称
            this.zwmcTextBox.Text = "";
            //外文名称
            this.wwmcTextBox.Text = "";
            //ICS分类
            this.icsflTextBox.Text = "";
            //GB分类
            this.gbflTextBox.Text = "";

            this.fbrqTextBox.Text = "";//发布日期
            this.ssrqTextBox.Text = nf + "-";//实施日期
            this.dtbzTextBox.Text = "";//代替标准
            this.bdtbzTextBox.Text = "";//被代替标准
            this.zfCheckBox.Checked = false;//作废
            this.zfnfTextBox.Text = "";//作废年份
            this.cygxTextBox.Text = ""; //采用关系
            this.ysTextBox.Text = "";//页数
            this.zwztcTextBox.Text = "";//中文主题词
            this.wwmcTextBox.Text = "";//外文主题词
            this.qcdwTextBox.Text = "";//起草单位
            this.fbdwTextBox.Text = "";//发布单位
            this.gkdwTextBox.Text = "";//归口单位
            this.bzdhhyTextBox.Text = "";//标准代号含义
            this.bzTextBox.Text = "";//备注
            this.lyTextBox.Text = "";//来源
            this.qrndTextBox.Text = "";//确认年代
            this.gxxTextBox.Text = "";//更新项

            //文件名
            this.pdfTextBox.Text = "";
        }
        else
        {
            //在现有基础上进行添加替代标准
            HYBZ_PM hybzPM = this.hybzDAO.GetHYBZ_PMByBzwh(bzwh);

            if (null == hybzPM)
            {
                message = "错误：没有找到该标准文号";
                Response.Redirect(GlobalResource.ERROR_PAGE + "?message=" + message);
                return;
            }

            //获取对应分类
            HYBZ_FL hybzFL = this.hybzDAO.GetHYBZ_FLByFlbm(hybzPM.flbm);
            //设置返回按钮链接
            this.backHyperLink.NavigateUrl = GlobalHYBZ.LISTPM_PAGE + "?catalog=" + hybzFL.flbm;

            //分类编码
            this.flbmTextBox.Text = hybzFL.flbm;
            //分类名称
            this.flmcTextBox.Text = hybzFL.flmc;
            //标准文号
            this.bzwhTextBox.Text = "";
            //实施年份
            this.ssnfTextBox.Text = "";

            //版本性质
            this.bbxzTextBox.Text = hybzPM.bbxz;
            //中文名称
            this.zwmcTextBox.Text = hybzPM.zwmc;
            //外文名称
            this.wwmcTextBox.Text = hybzPM.wwmc;
            //ICS分类
            this.icsflTextBox.Text = hybzPM.icsfl;
            //GB分类
            this.gbflTextBox.Text = hybzPM.gbfl;

            this.fbrqTextBox.Text = "";//发布日期
            this.ssrqTextBox.Text = "";//实施日期
            this.dtbzTextBox.Text = hybzPM.bzwh;//代替标准
            this.bdtbzTextBox.Text = "";//被代替标准
            this.zfCheckBox.Checked = hybzPM.zf;//作废
            this.zfnfTextBox.Text = hybzPM.zfnf;//作废年份
            this.cygxTextBox.Text = hybzPM.cygx; //采用关系
            this.ysTextBox.Text = hybzPM.ys.ToString();//页数
            this.zwztcTextBox.Text = hybzPM.zwztc;//中文主题词
            this.wwmcTextBox.Text = hybzPM.wwztc;//外文主题词
            this.qcdwTextBox.Text = hybzPM.qcdw;//起草单位
            this.fbdwTextBox.Text = hybzPM.fbdw;//发布单位
            this.gkdwTextBox.Text = hybzPM.gkdw;//归口单位
            this.bzdhhyTextBox.Text = hybzPM.bzdhhy;//标准代号含义
            this.bzTextBox.Text = hybzPM.bz;//备注
            this.lyTextBox.Text = hybzPM.ly;//来源
            this.qrndTextBox.Text = hybzPM.qrnd;//确认年代
            this.gxxTextBox.Text = hybzPM.gxx;//更新项
            this.pdfTextBox.Text = "";//文件名
        }
    }

    /// <summary>
    /// 获取用户填写的行业标准篇名信息
    /// </summary>
    /// <returns></returns>
    private HYBZ_PM GetHYBZPM()
    {
        HYBZ_PM hybzPM = new HYBZ_PM();
        //标准文号
        hybzPM.bzwh = this.bzwhTextBox.Text.Trim();
        //分类编码
        hybzPM.flbm = this.flbmTextBox.Text;
        //文件名
        hybzPM.wjm = this.pdfTextBox.Text;
        //中文名称
        hybzPM.zwmc = this.zwmcTextBox.Text.Trim();
        //版本性质
        hybzPM.bbxz = this.bbxzTextBox.Text.Trim();
        //ICS分类
        hybzPM.icsfl = this.icsflTextBox.Text.Trim();
        //GB分类
        hybzPM.gbfl = this.gbflTextBox.Text.Trim();
        //外文名称
        hybzPM.wwmc = this.wwmcTextBox.Text.Trim();
        //发布日期
        if (!"".Equals(this.fbrqTextBox.Text))
        {
            hybzPM.fbrq = DateTime.Parse(this.fbrqTextBox.Text);
        }
        //实施日期
        if (!"".Equals(this.ssrqTextBox.Text))
        {
            hybzPM.ssrq = DateTime.Parse(this.ssrqTextBox.Text);
        }
        //采用关系
        hybzPM.cygx = this.cygxTextBox.Text.Trim();
        //代替标准
        hybzPM.dtbz = this.dtbzTextBox.Text.Trim();
        //被代替标准
        hybzPM.bdtbz = this.bdtbzTextBox.Text.Trim();
        //页数
        if (!"".Equals(this.ysTextBox.Text))
            hybzPM.ys = Int32.Parse(this.ysTextBox.Text);
        //作废
        hybzPM.zf = this.zfCheckBox.Checked;
        //作废年份
        hybzPM.zfnf = this.zfnfTextBox.Text.Trim();
        //中文主题词
        hybzPM.zwztc = this.zwmcTextBox.Text.Trim();
        //外文主题词
        hybzPM.wwztc = this.wwztcTextBox.Text.Trim();
        //起草单位
        hybzPM.qcdw = this.qcdwTextBox.Text.Trim();
        //发布单位
        hybzPM.fbdw = this.fbdwTextBox.Text.Trim();
        //归口单位
        hybzPM.gkdw = this.gkdwTextBox.Text.Trim();
        //备注
        hybzPM.bz = this.bzTextBox.Text.Trim();
        //标准代号含义
        hybzPM.bzdhhy = this.bzdhhyTextBox.Text.Trim();
        //来源
        hybzPM.ly = this.lyTextBox.Text.Trim();
        //更新项
        hybzPM.gxx = this.gxxTextBox.Text.Trim();
        //确认年代
        hybzPM.qrnd = this.qrndTextBox.Text.Trim();
        //更新日期
        hybzPM.gxrq = DateTime.Now;
        //登录人
        hybzPM.dlr = this.dlrTextBox.Text;


        return hybzPM;

    }

    /// <summary>
    /// 获取下一个文件名，不包括后缀
    /// </summary>
    /// <param name="wjm"></param>
    /// <returns></returns>
    private String GetWJM(String wjm)
    {
        String result = null;
        if (null == wjm || "".Equals(wjm))
        {
            result = this.bzwhTextBox.Text + "-0001";
        }
        else
        {
            //获取文件名的后四位流水号，并在其基础上加1
            int endIndex = wjm.LastIndexOf(".");

            String phString = wjm.Substring(endIndex - 4, 4);

            int ph = 0;

            try
            {
                ph = Int32.Parse(phString);
            }
            catch (Exception)
            {
            }

            //当前篇号+1
            ph += 1;

            phString = ph.ToString();
            //长度为1
            if (phString.Length == 1)
            {
                phString = "000" + phString;
            }
            else if (phString.Length == 2)
            {
                phString = "00" + phString;
            }
            else if (phString.Length == 3)
            {
                phString = "0" + phString;
            }
            else if (phString.Length >= 3)
            {
                String message = "错误：篇名数量已经超过了1000篇";
                Response.Redirect(GlobalResource.ERROR_PAGE + "?message=" + message);
                return null;
            }

            result = this.bzwhTextBox.Text + "-" + phString;
        }
        return result;
    }

    protected void submitButton_Click(object sender, EventArgs e)
    {
        //验证标准文号
        if (!this.ValidateBZWH())
        {
            return;
        }
        //验证中文名称
        if (!this.ValidateZWMC())
        {
            return;
        }
        //验证实施日期
        if (!this.ValidateSSRQ())
        {
            return;
        }
        //验证发布日期
        if (!this.ValidateFBRQ())
        {
            return;
        }
        //验证页数
        if (!this.ValidateYS())
        {
            return;
        }
        //验证上传文件
        if (!this.ValidateYWJMFileUpload())
        {
            return;
        }
        //验证代替标准
        if (!this.ValidateDTBZ(this.dtbzTextBox.Text))
        {
            return;
        }
        //验证被代替标准
        if (!this.ValidateDTBZ(this.bdtbzTextBox.Text))
        {
            return;
        }

        //检查需要代替的标准,代替标准文号相同，但年份较早的标准
        this.CheckBZDT(this.bzwhTextBox.Text);

        HYBZ_PM hybzPM = this.GetHYBZPM();

        if (null != this.ywjmFileUpload.FileName && !"".Equals(this.ywjmFileUpload.FileName))
        {
            if (!OperationFile.Upload(this.ywjmFileUpload, hybzPM.wjm))
            {
                Response.Write("<Script>alert('添加行业标准信息失败')</Script>");
                return;
            }
        }

        if (this.hybzDAO.InsertHYBZ_PM(hybzPM))
        {
            //更新被替代标准的作废字段
            if (!"".Equals(this.dtbzTextBox.Text))
                UpdateTdbz(this.dtbzTextBox.Text, this.bzwhTextBox.Text);
            //更新替代标准信息
            if (!"".Equals(this.bdtbzTextBox.Text))
                UpdateBtdbz(this.bdtbzTextBox.Text, this.bzwhTextBox.Text);

            Response.Write("<Script>alert('添加行业标准信息成功')</Script>");
        }
        else
            Response.Write("<Script>alert('添加行业标准信息失败')</Script>");
    }

    //更新替代标准信息
    private void UpdateTdbz(String bzs, String bzwh)
    {
        String[] str = bzs.Split(';');
        for (int i = 0; i < str.Length; i++)
        {
            HYBZ_PM hybzPM = this.hybzDAO.GetHYBZ_PMByBzwh(str[i]);
            if (hybzPM == null) continue;
            
            hybzPM.zf = true;
            if (null == hybzPM.bdtbz || "".Equals(hybzPM.bdtbz))
                hybzPM.bdtbz = bzwh;
            else if (hybzPM.bdtbz.IndexOf(bzwh) < 0)//原被替代标准关系中不存在，则加上
            {
                hybzPM.bdtbz = hybzPM.bdtbz + ";" + bzwh;
            }
            //作废年份为更新标准的年份
            String[] bnf = bzwh.Split('-');
            hybzPM.zfnf = bnf[bnf.Length - 1];

            //进行更新
            this.hybzDAO.UpdateHYBZ_PM(hybzPM, ((User)Session["login"]).name);
        }
    }

    //更新被替代标准信息
    private void UpdateBtdbz(String bzs, String bzwh)
    {
        String[] str = bzs.Split(';');
        for (int i = 0; i < str.Length; i++)
        {
            HYBZ_PM hybzPM = this.hybzDAO.GetHYBZ_PMByBzwh(str[i]);
            if (hybzPM == null) continue;

            if (null == hybzPM.dtbz || "".Equals(hybzPM.dtbz))
                hybzPM.dtbz = bzwh;
            else if (hybzPM.dtbz.IndexOf(bzwh) < 0)//原被替代标准关系中不存在，则加上
            {
                hybzPM.dtbz = hybzPM.dtbz + ";" + bzwh;
            }

            //进行更新
            this.hybzDAO.UpdateHYBZ_PM(hybzPM, ((User)Session["login"]).name);
        }
    }

    //验证需要代替的标准
    private void CheckBZDT(String bzwh)
    {
        String prefix = bzwh.Split('-')[0];//取出除去年份的文号
        HYBZ_PM hybz = this.hybzDAO.GetAlikeHYBZ_PM(prefix+"-");

        if (null != hybz)
        {
            if ("".Equals(this.dtbzTextBox.Text))
            {
                this.dtbzTextBox.Text = hybz.bzwh;
            }
            else if (this.dtbzTextBox.Text.IndexOf(hybz.bzwh) >= 0) //原来替代标准中已经包含该需要替代标准
            {
                //Do nothing
            }
            else //添加需要替代的标准
            {
                this.dtbzTextBox.Text = this.dtbzTextBox.Text + ";" + hybz.bzwh;
            }

            if (null == hybz.bdtbz || "".Equals(hybz.bdtbz))
                hybz.bdtbz = bzwh;
            else if (hybz.bdtbz.IndexOf(bzwh) < 0)
            {
                hybz.bdtbz = hybz.bdtbz + ";" + bzwh;
            }
            //作废为真
            hybz.zf = true;
            //作废年份为更新标准的年份
            String[] bnf = bzwh.Split('-');
            hybz.zfnf = bnf[bnf.Length -1];

            //进行更新
            this.hybzDAO.UpdateHYBZ_PM(hybz, ((User)Session["login"]).name);
        }
    }

    /// <summary>
    /// 验证标准编号
    /// </summary>
    /// <returns></returns>
    private Boolean ValidateBZWH()
    {
        Boolean flag = true;

        this.errorLabel.Text = "";
        HYBZ_PM hybzPM = this.hybzDAO.GetHYBZ_PMByBzwh(this.bzwhTextBox.Text);
        if (null != hybzPM)
        {
            this.errorLabel.Text = "错误：该标准文号已存在";
            flag = false;
        }
        return flag;
    }

    /// <summary>
    /// 验证中文名称
    /// </summary>
    /// <returns></returns>
    private Boolean ValidateZWMC()
    {
        Boolean flag = true;

        this.errorLabel.Text = "";
        if(null==this.zwmcTextBox.Text||"".Equals(this.zwmcTextBox.Text.Trim()))
        {
            this.errorLabel.Text = "错误：中文名称不能为空";
            flag = false;
        }
        return flag;
    }

    /// <summary>验证发布日期</summary>
    private Boolean ValidateFBRQ()
    {
        this.errorLabel.Text = "";

        Boolean flag = true;
        if (this.fbrqTextBox != null && this.fbrqTextBox.Text != "")
        {
            try
            {
                DateTime val = DateTime.Parse(this.fbrqTextBox.Text);
            }
            catch (Exception)
            {
                this.errorLabel.Text = "错误：发布日期格式不正确(yyyy-MM-dd)";
                return false;
            }
        }

        return flag;
    }

    /// <summary>验证实施日期</summary>
    private Boolean ValidateSSRQ()
    {
        this.errorLabel.Text = "";

        Boolean flag = true;
        if (this.ssrqTextBox != null && this.ssrqTextBox.Text != "")
        {
            try
            {
                DateTime val = DateTime.Parse(this.ssrqTextBox.Text);
                String nf = val.Year.ToString();
                if (!nf.Equals(this.bzwhTextBox.Text.Split('-')[1])) {
                    this.errorLabel.Text ="错误：标准文号的年份与实施年份不符";
                    return false;
                }
            }
            catch (Exception)
            {
                this.errorLabel.Text = "错误：实施日期格式不正确(yyyy-MM-dd)";
                return false;
            }
        }

        return flag;
    }

    /// <summary>验证页数</summary>
    private Boolean ValidateYS()
    {
        this.errorLabel.Text = "";

        Boolean flag = true;
        if (this.ysTextBox != null && this.ysTextBox.Text != "")
        {
            try
            {
                int val = Int32.Parse(this.ysTextBox.Text);
            }
            catch (Exception)
            {
                this.errorLabel.Text = "错误：页数信息不是有效数字";
                return false;
            }
        }

        return flag;
    }
    ///<summary>验证代替标准是否存在</summary>
    private Boolean ValidateDTBZ(String dtbz)
    {
        Boolean flag = true;
        if (null == dtbz || "".Equals(dtbz)) return flag;

        String[] bzs = dtbz.Split(';');
        for (int i = 0; i < bzs.Length; i++)
        {
            HYBZ_PM hybz = this.hybzDAO.GetHYBZ_PMByBzwh(bzs[i]);
            if (null == hybz)
            {
                this.errorLabel.Text = "错误：该代替标准("+bzs[i]+")不存在，请核实";
                return false;
            }
        }

        return flag;
    }

    ///<summary>构造出文件名</summary>
    ///<param name="bzwh">标准文号</param>
    ///<param name="bbxz>版本性质</param>
    private String ConstructWJM(String bzwh, String bbxz)
    {
        String wjm = null;
        int times = 0;

        for (int i = 0; i < bzwh.Length; i++)
        {
            //第一个空格
            if (bzwh[i] == ' ' && times == 0)
            {
                wjm = wjm + "_";//替换空格
                if (null != bbxz && !"".Equals(bbxz)) bbxz = bbxz + "_";
                wjm = wjm + bbxz;//连接版本性质
                times = 1;
                continue;
            }

            if (bzwh[i] == ' ' && times > 0)
            {
                wjm = wjm + "_";
                continue;
            }

            if (bzwh[i] == '.')
            {
                wjm = wjm + "~";
                continue;
            }

            wjm = wjm + bzwh[i];
        }

        wjm = wjm + ".PDF";

        return wjm;
    }
    /// <summary>
    /// 验证上传文件
    /// </summary>
    /// <returns></returns>
    private Boolean ValidateYWJMFileUpload()
    {
        this.errorLabel.Text = "";
        Boolean flag = true;
        if (null == this.ywjmFileUpload || !this.ywjmFileUpload.HasFile)
        {
        }
        else
        {
            if (!this.ywjmFileUpload.FileName.EndsWith(".PDF", true, null))
            {
                this.errorLabel.Text = "错误：请选择PDF类型文件";
                flag = false;
            }
            else
            {
                PdfReader pdf = new PdfReader(this.ywjmFileUpload.FileBytes);
                if (null != pdf)
                {
                    //文件大小不能超过10M
                    if (pdf.FileLength >= 10 * 1024 * 1024)
                    {
                        this.errorLabel.Text = "错误：选择的文件大小超过了10M";
                        pdf.Close();
                        return false;
                    }

                    this.ysTextBox.Text = pdf.NumberOfPages.ToString();
                    this.pdfTextBox.Text = ConstructWJM(this.bzwhTextBox.Text, this.bbxzTextBox.Text);
                }

                pdf.Close();
            }
        }
        return flag;
    }

    //全角转半角
    protected void resetButton_Click(object sender, EventArgs e)
    {
        this.BindData();
    }
    protected void icsflTextBox_TextChanged(object sender, EventArgs e)
    {
        this.icsflTextBox.Text = GlobalMethod.Semicolon(this.icsflTextBox.Text.Trim());
    }
    protected void gbflTextBox_TextChanged(object sender, EventArgs e)
    {
        this.gbflTextBox.Text = GlobalMethod.Semicolon(this.gbflTextBox.Text.Trim());
    }
    protected void zwztcTextBox_TextChanged(object sender, EventArgs e)
    {
        this.zwztcTextBox.Text = GlobalMethod.Semicolon(this.zwztcTextBox.Text.Trim());
    }
    protected void wwztcTextBox_TextChanged(object sender, EventArgs e)
    {
        this.wwztcTextBox.Text = GlobalMethod.Semicolon(this.wwztcTextBox.Text.Trim());
    }
    protected void dtbzTextBox_TextChanged(object sender, EventArgs e)
    {
        this.dtbzTextBox.Text = GlobalMethod.Semicolon(this.dtbzTextBox.Text.Trim());
    }
    protected void bdtbzTextBox_TextChanged(object sender, EventArgs e)
    {
        this.bdtbzTextBox.Text = GlobalMethod.Semicolon(this.bdtbzTextBox.Text.Trim());
    }
    //规范标准文号
    protected void bzwhTextBox_TextChanged(object sender, EventArgs e)
    {
        this.bzwhTextBox.Text = GlobalMethod.Semicolon(this.bzwhTextBox.Text.Trim());
        String bzwh = this.bzwhTextBox.Text;

        bzwh.Replace('/', ' ');
        String new_bzwh = "";
        //去掉非法字符
        for (int i = 0; i < bzwh.Length; i++)
        {
            if ((bzwh[i] >= 'A' && bzwh[i] <= 'Z')
                || (bzwh[i] >= 'a' && bzwh[i] <= 'z')
                || (bzwh[i] >= '0' && bzwh[i] <= '9')
                || bzwh[i] == ' ' 
                || bzwh[i] == '-'
                || bzwh[i] == '.')
            {
                new_bzwh += bzwh[i];
            }
        }
        //加空格
        bzwh = "";
        for (int i = 0; i < new_bzwh.Length-1; i++)
        {
            bzwh = bzwh + new_bzwh[i];
            if ((new_bzwh[i] >= 'A' && new_bzwh[i] <= 'Z')
                || (new_bzwh[i] >= 'a' && new_bzwh[i] <= 'z'))
            {
                if (new_bzwh[i + 1] <= '9' && new_bzwh[i+1] >= '0')
                {
                    bzwh = bzwh + ' ';
                }
            }
        }
        bzwh = bzwh + new_bzwh[new_bzwh.Length - 1];

        this.bzwhTextBox.Text = bzwh;
    }
}